<template>
  <div style="overflow-y: auto;height: 100vh;">
    <el-steps :active="detailsItem.newProcessing?.codeIndex" :finish-status="detailsItem.newProcessing?.isCanceled"
      align-center>
      <el-step :title="detailsItem.newProcessing?.codeName">

        <template #description>
          <p class="publicTop">{{ detailsItem.newProcessing?.timeName }}</p>
          <p class="publicTop">{{ detailsItem.newProcessing?.time }}</p>
        </template>
      </el-step>
      <el-step :title="detailsItem.newProcessing?.procurementName">
        <template #description>
          <div v-if="detailsItem.newProcessing?.isProcurementTime">
            <p class="publicTop">{{ detailsItem.newProcessing?.procurementTimeName }}</p>
            <p class="publicTop">{{ detailsItem.newProcessing?.paymentTime }}</p>
          </div>
          <el-button type="primary" @click="handleClick(4)"
            v-if="detailsItem.newProcessing?.isProcurement">采购完成</el-button>
        </template>
      </el-step>

      <el-step :title="detailsItem.newProcessing?.shippedName">
        <template #description>
          <div v-if="detailsItem.newProcessing?.deliverTime">
            <p class="publicTop">{{ detailsItem.newProcessing?.deliverTimeName }}</p>
            <p class="publicTop">{{ detailsItem.newProcessing?.deliverTime }}</p>
          </div>
          <el-button type="primary" @click="handleClick(3)" v-if="detailsItem.newProcessing?.isDeliver">发货</el-button>
        </template>
      </el-step>

      <el-step title="待收货">

      </el-step>

      <el-step :title="detailsItem.newProcessing?.Successful">
        <template #description>
          <p class="publicTop">交易完成时间</p>
          <p class="publicTop">{{ detailsItem.newProcessing?.SuccessfulTime }}</p>
        </template>
      </el-step>
    </el-steps>



    <el-descriptions :column="4" title="订单信息" style="margin: 0 5% 20px 5%;" border size="large">
      <el-descriptions-item label="订单编号">{{
        detailsItem.orderCode || "-"
      }}</el-descriptions-item>
      <el-descriptions-item label="优惠方式">{{
        detailsItem.preferentialMode || "-"
      }}</el-descriptions-item>

      <el-descriptions-item label="支付方式">{{
        payItem.paymentMode || "-"
      }}</el-descriptions-item>
      <el-descriptions-item label="发货时间">{{
        transitItem.newCreated
      }}</el-descriptions-item>

      <el-descriptions-item label="站点id">{{
        detailsItem.websiteId || "-"
      }}</el-descriptions-item>
      <el-descriptions-item label="优惠金额">{{
        detailsItem.preferentialAmount || '0'
      }}</el-descriptions-item>
      <el-descriptions-item label="支付单号">{{
        payItem.payRequestId || "-"
      }}</el-descriptions-item>
      <el-descriptions-item label="发货物流">
        <!-- 货运方式 -->
        {{
          transitItem.freightMode || "-"
        }}</el-descriptions-item>

      <el-descriptions-item label="站点名称">{{
        detailsItem.shopSiteName || "-"
      }}</el-descriptions-item>
      <el-descriptions-item label="货运方式">{{
        detailsItem.freightMode || "-"
      }}</el-descriptions-item>

      <el-descriptions-item label="支付时间：">{{
        payItem.newPayTime
      }}</el-descriptions-item>

      <el-descriptions-item label="物流单号">
        <!-- 运单号 -->
        {{
          transitItem.freightCode || "-"
        }}</el-descriptions-item>

      <el-descriptions-item label="商品总价">
        {{
          detailsItem.productAmount || '-'
        }}</el-descriptions-item>

      <el-descriptions-item label="运费金额">
        <!-- 运费 -->
        {{
          detailsItem.freightAmount || "-"
        }}</el-descriptions-item>

      <el-descriptions-item label="支付金额">
        {{
          payItem.payAmount || "-"
        }}</el-descriptions-item>

      <el-descriptions-item label="物流状态">-
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions title="收货信息" :column="2" border style="margin: 0 5% 20px 5%;">
      <el-descriptions-item label="收货地址">
        <el-space spacer=" " wrap style="width: 200px;">
          <el-text>{{ detailsItem.receiveName }}</el-text>
          <el-text>{{ detailsItem.receiveCountry }}</el-text>
          <el-text>{{ detailsItem.receiveAddressContent }}</el-text>
          <el-text>{{ detailsItem.receivePostcode }}</el-text>
        </el-space>
      </el-descriptions-item>

      <el-descriptions-item label="账单地址">
        <el-space spacer=" " wrap style="width: 200px;">
          <el-text>{{ detailsItem.billingName }}</el-text>
          <el-text>{{ detailsItem.billingCountry || '-' }}</el-text>
          <el-text>{{ detailsItem.billingAddressContent || '-' }}</el-text>
          <el-text>{{ detailsItem.billingPostcode == null ? '-' : detailsItem.billingPostcode }}</el-text>
        </el-space>
      </el-descriptions-item>

    </el-descriptions>
    <el-descriptions title="商品信息" style=" margin: 0 5%" />
    <el-table :data="productList" style="width: 90%;margin: auto">
      <el-table-column prop="productId" label="ID" width="150"/>
      <el-table-column prop="orderStatus" label="商品" width="300">
        <template #default="scope">
          <el-space spacer=" ">
            <image-preview :src="scope.row.newImage" fit="scale-down" :width="100" :height="100" />
            <el-link :href="scope.row.productUrl" target="_blank">{{
              scope.row.name
            }}</el-link>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column prop="optionValues" label="规格" width="200">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-button v-for="(item, index) in scope.row.optionValues" :key="index" type="primary" size="small">
              <el-text class="w-150px mb-2" truncated style="color: #fff;"> {{ item }}</el-text>
            </el-button>
          </el-space>

        </template>
      </el-table-column>

      <el-table-column prop="productCount" label="数量" align="center" width="100" />
      <el-table-column label="售价" width="150">
        <template #default="scope">
          <el-space spacer="-">
            <!-- 售价 -->
            <el-text>{{ scope.row.sellPrice }}</el-text>
            <el-text>{{ scope.row.gatherCurrencyDescription }}</el-text>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column prop="source" label="商品来源" align="center">
        <template #default="scope">
          <el-link :href="scope.row.rawUrl" target="_blank">{{
            scope.row.collectionSiteName || "1688"
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="gatherPrice" label="入库价" width="150">
        <template #default="scope">
          <el-tooltip placement="top">
            <template #content>
              <div>
                {{ scope.row.gatherCurrencyDescription }}：{{
                  scope.row.gatherPrice }} {{ scope.row.gatherSymbol
                }}
                <br />
                人民币：{{ scope.row.cnyprice }} ￥
              </div>
            </template>
            <el-space spacer=" " wrap>
              <el-space spacer=" ">
                <el-text>{{ scope.row.gatherPrice }}</el-text>
                <el-text>{{ scope.row.gatherSymbol }}</el-text>
              </el-space>
              <el-space spacer=" ">
                <el-text>{{ scope.row.cnyprice }}</el-text>
                <el-text>￥</el-text>
              </el-space>
            </el-space>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="采购信息" width="200">
        <template #default="scope">
          <div class="publicStart">
            <el-text>采购状态：
              <el-tag :type="scope.row.newProcureStatus?.elTagClass"> {{ scope.row.newProcureStatus
                ?.label }}</el-tag>
            </el-text>
            <el-text>采购单号：{{ scope.row.procureCode || '-' }}</el-text>
            <el-text>采购单价：{{ scope.row.procurePrice || '-' }}
              {{ scope.row.procureCurrencyDescription }}</el-text>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="采购物流信息" width="200">
        <template #default="scope">
          <div class="publicStart">
            <el-text>采购物流：{{ scope.row.transportName }}</el-text>
            <el-text>物流单号：{{ scope.row.logisticsCode }}</el-text>
            <el-text>运费价格：{{ scope.row.freightAmount }} {{ scope.row.procureCurrencyDescription || '-' }}</el-text>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleClick(0, scope.row)">查看</el-button>
          <el-button type="primary" size="small" @click="handleClick(1, scope.row)" v-if="scope.row.showView">
            采购
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-descriptions title="操作记录" style="margin: 0 5%;" />
    <el-table :data="operationList" style=" margin: 0 5% 20px 5%;">
      <el-table-column prop="newOperateTime" label="时间" align="center" width="200" />
      <el-table-column prop="username" label="操作人" align="center" width="300" />
      <el-table-column prop="operateTime" label="操作节点" align="center" width="200" />
      <el-table-column prop="operateContent" label="操作内容" />
    </el-table>
    <OrderDetails :showIndex="showIndex" @handleSure="handleSure" @handleClose="handleClose" :publicItem="publicItem"
      :publicDialog="publicDialog"></OrderDetails>
  </div>
</template>
<script setup>
import { useRoute } from "vue-router";
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import OrderDetails from "./components/orderBullet.vue";
const { proxy } = getCurrentInstance();
const { order_status, procure_status } = proxy.useDict(
  "order_status",
  "procure_status"
);
const route = useRoute();
const productList = ref([]); //商品信息
const operationList = ref([]); //操作记录
const detailsItem = ref({});
const transitItem = ref({}); //中转信息数据
const payItem = ref({}); //支付信息
// 弹框字段
const showIndex = ref(null);
const publicItem = ref({}); //公共赋值对象
const publicDialog = ref(false);

onMounted(() => {
  getOrderDetails();
  transit();
});
// 获取详情
const getOrderDetails = () => {
  let from = {
    id: route.query.id,
    operationType: route.query.operationType,
  };

  order.order
    .orderGetbyid({
      data: from,
    })
    .then((res) => {
      if (res.code !== 200) return;
      res.data = {
        ...res.data,
        receiveName: `${res.data.receivingAddress.name}          （${res.data.receivingAddress.phonePrefix} ${res.data.receivingAddress.phone}）`,
        receiveCountry: `${res.data.receivingAddress.countryName} ${res.data.receivingAddress.countryZoneName}`,
        receiveAddressContent: `${res.data.receivingAddress.addressContent} `,
        receivePostcode: `${res.data.receivingAddress.postcode || '-'} `,
        // billingAddress账单地址
        billingName: `${res.data.billingAddress.name}          （${res.data.billingAddress.phonePrefix} ${res.data.billingAddress.phone}）`,
        billingCountry: `${res.data.billingAddress.countryName} ${res.data.billingAddress.countryZoneName}`,
        billingAddressContent: `${res.data.billingAddress.addressContent} `,
        billingPostcode: `${res.data.billingAddress.postcode || '-'} `,

        isCanceled: res.data.orderStatus === 'canceled',//是取消代表是false
        newProcessing: processing(res.data),
        newCreated: proxy.DateTime(res.data.created), //下单时间
        newPayTime: proxy.DateTime(res.data.payTime), //支付时间
        newProcureTime: proxy.DateTime(res.data.procureTime), //采购时间
        newShipmentTime: proxy.DateTime(res.data.shipmentTime), //发货时间
        newCompleteTime: proxy.DateTime(res.data.completeTime), //交易完成时间时间
        newOrderStatus: order_status.value.find(
          (e) => e.value === res.data.orderStatus
        )?.label,
      };
      detailsItem.value = res.data;
      getProductList();

      console.log(detailsItem.value, "详情");
    });
};
// 商品信息列表
const getProductList = () => {
  order.order
    .orderProductlist({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          orderId: Number(route.query.id),
        },
      },
    })
    .then((res) => {
      if (!res.data?.length) return (productList.value = []);
      res.data = res.data.map((code) => {
        console.log(detailsItem.value.orderStatus);
        return {
          ...code,
          newImage: handleImage(code),
          sourceSiteStatus: code.sourceSiteStatus === null ? false : code.sourceSiteStatus,
          showView:
            detailsItem.value.orderStatus === 'wait_procure', // 订单待付款和订单待付款不显示查看功能
          newProcureStatus: procure_status.value.find(
            (e) => e.value === code.procureStatus
          ),
        };
      });
      productList.value = res.data;
      console.log(productList.value, "商品列表信息");
    });
};
const transit = () => {
  // 中转信息
  order.order
    .orderGetdeliveries({
      pathParams: {
        orderId: Number(route.query.id),
      },
    })
    .then((res) => {
      res.data = {
        ...res.data,
        newCreated: proxy.DateTime(res.data.created),
      };
      transitItem.value = res.data;
      // console.log(res.data, "中转信息");
    });
  // 支付信息
  order.order
    .orderGetpaymentinfo({
      pathParams: {
        orderId: Number(route.query.id),
      },
    })
    .then((res) => {
      res.data = {
        ...res.data,
        newPayTime: proxy.DateTime(res.data.payTime),
      };
      payItem.value = res.data;
      console.log(res.data, "支付信息");
    });
  // 操作记录数据==>订单==》orderOperateLogs
  order.general
    .orderoperatelogsList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          orderId: Number(route.query.id),
        },
      },
    })
    .then((res) => {
      if (!res.data?.length) return (operationList.value = []);
      res.data = res.data.map((code) => {
        return {
          ...code,
          newOperateTime: proxy.DateTime(code.operateTime)
            ,
        };
      });
      operationList.value = res.data;
      // console.log(res.data, "操作记录数据");
    });
};

const handleClick = (index, rowItem) => {
  showIndex.value = index;

  if (index === 1) {
    console.log(rowItem);
    publicItem.value = rowItem;
    publicDialog.value = true;
    //采购
  } else if (index === 3) {
    //发货
    publicItem.value = {
      id: Number(route.query.id)
    };
    publicDialog.value = true;
  } else if (index === 4) {
    //采购完成
    proxy.$modal.confirm("是否确认采购完成？").then(() => {
      order.order
        .orderProcurecomplete({
          data: {
            id: route.query.id,
          },
        })
        .then((res) => {
          if (res.code !== 200) return;
          getOrderDetails();
          transit();
        });
    });
  } else {
    //查看
    publicItem.value = rowItem;
    publicDialog.value = true;
  }
};
const handleSure = () => {
  publicDialog.value = false;
  getOrderDetails();
  transit();
};
const handleClose = () => {
  publicDialog.value = false;
};

const processing = (rowItem) => {
  // console.log(rowItem.orderStatus, '[[[[[[]]]]]]', rowItem.payTime);
  if (rowItem.orderStatus === "wait_pay") {
    return { //待付款
      isCanceled: 'success',
      codeIndex: 0,
      codeName: '待付款',
      timeName: '下单时间',
      time: proxy.DateTime(rowItem.created),
      procurementName: '待采购',
      isProcurementTime: true,
      procurementTimeName: '',
      paymentTime: '',
      shippedName: '待发货',
      Successful: '交易成功',
      SuccessfulTime: ''
    }
  } else if (rowItem.orderStatus === "closed") {
    return { //待付款
      codeIndex: 1,
      codeName: '交易关闭',
      isCanceled: 'error',
      timeName: '关闭时间',
      time: proxy.DateTime(rowItem.lastModified),
      procurementName: '待采购',
      isProcurementTime: false,
      isProcurement: false,
      shippedName: '待发货',
      isDeliver: false,//不显示发货
      deliverTimeName: '发货时间',
      deliverTime: '',
      Successful: '交易成功',
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)
    }
  } else if (rowItem.orderStatus === "wait_procure") {
    return {
      codeIndex: 1,
      codeName: '支付完成',
      isCanceled: 'success',
      timeName: '支付时间',
      time: proxy.DateTime(rowItem.payTime), //支付时间
      isProcurement: true,
      procurementName: '待采购',
      isProcurementTime: false,
      procurementName: '采购时间',
      procurementTimeName: '支付时间',
      shippedName: '待发货',
      isDeliver: false,//不显示发货
      deliverTimeName: '发货时间',
      deliverTime: '',
      Successful: '交易成功',
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)


    }
  } else if (rowItem.orderStatus === "wait_shipped") {
    return {
      isCanceled: 'success',
      codeIndex: 2,
      codeName: '支付完成',
      timeName: '支付时间',
      time: proxy.DateTime(rowItem.procureTime), //采购时间
      paymentTime: proxy.DateTime(rowItem.procureTime),
      isProcurement: false,
      procurementName: '采购完成',
      procurementTimeName: '采购时间',
      isProcurementTime: true,
      isShipped: true,
      shippedName: '待发货',
      isDeliver: true,//显示发货
      deliverTimeName: '发货时间',
      deliverTime: '',
      Successful: '交易成功',
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)


    }
  } else if (rowItem.orderStatus === "wait_receipt") {
    return {
      isCanceled: 'success',
      codeIndex: 3,
      codeName: '支付完成',
      timeName: '支付时间',
      time: proxy.DateTime(rowItem.payTime), //支付时间
      paymentTime: proxy.DateTime(rowItem.procureTime),

      isProcurement: false,
      procurementName: '采购完成',
      procurementTimeName: '采购时间',
      isProcurementTime: true,
      isShipped: true,
      shippedName: '发货完成',
      isDeliver: false,//显示发货
      deliverTimeName: '发货时间',
      deliverTime: proxy.DateTime(rowItem.shipmentTime),
      Successful: '交易成功',
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)
    }
  } else if (rowItem.orderStatus === "succeed") {
    return {
      isCanceled: 'success',
      codeIndex: 5,
      codeName: '支付完成',
      procurementName: '采购完成',
      shippedName: '发货完成',
      Successful: '交易成功',
      timeName: '支付时间',
      time: proxy.DateTime(rowItem.payTime), //支付时间
      procurementTimeName: '采购时间',
      paymentTime: proxy.DateTime(rowItem.procureTime),
      isProcurementTime: true,
      deliverTimeName: '发货时间',
      deliverTime: proxy.DateTime(rowItem.shipmentTime),
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)
    }

  } else if (rowItem.orderStatus === "canceled") {
    return {
      codeIndex: 1,
      codeName: '交易取消',
      isCanceled: 'error',
      timeName: '下单时间',
      time: proxy.DateTime(rowItem.lastModified),
      procurementName: '待采购',
      isProcurementTime: false,
      isProcurement: false,
      shippedName: '待发货',
      isDeliver: false,//不显示发货
      deliverTimeName: '发货时间',
      deliverTime: '',
      Successful: '交易成功',
      SuccessfulTime: proxy.DateTime(rowItem.completeTime)
    }
  }
  // if (rowItem.orderStatus === "canceled") {
  //   codeIndex = 1; //已取消
  // } else if (rowItem.orderStatus === "wait_pay") {
  //   codeIndex = 1; //待付款
  // } else if (rowItem.orderStatus === "wait_procure") {
  //   codeIndex = 2; //待采购
  // } else if (rowItem.orderStatus === "wait_shipped") {
  //   codeIndex = 3; //待中转
  // } else if (rowItem.orderStatus === "wait_receipt") {
  //   codeIndex = 4; //待收货
  // } else if (rowItem.orderStatus === "succeed") {
  //   codeIndex = 5; //交易成功
  // } else if (rowItem.orderStatus === "closed") {
  //   codeIndex = 1; //closed
  // }
  // return codeIndex;
};
const handleImage = (row) => {
  var imageExtensionsRegex = /^https?:\/\//i;
  if (!imageExtensionsRegex.test(row.mainImage)) {
    return row.host
  } else {
    return row.mainImage
  }
}
</script>

<style scoped lang="scss">
.optionValues {
  display: flex;
  flex-direction: column;
  gap: 10px;
  border-radius: 5px;

  >div {
    border: 1px solid #eee;
    padding: 5px 0;
    cursor: pointer;
  }
}

.eighteen {
  font-size: 18px;
}

:deep(.el-step__title) {
  font-size: 18px;
}

.publicTop {
  font-size: 11px;
  margin-top: -5px;
}

.custom-descriptions {
  width: 80px;
}

/* 隐藏滚动条（适用于 Chrome、Safari） */
::-webkit-scrollbar {
  display: none;
}

.publicStart {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  justify-content: flex-start;
  /* 左对齐 */
  gap: 10px;
  /* 设置元素之间的间隔 */
}
</style>